from api.database import db


# 作者信息模型
class Author(db.Model):
    __tablename__ = 'authors'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    created = db.Column(db.DateTime, server_default=db.func.now())
    # 将 cascade 配置移到 books 关系中
    books = db.relationship('Book', backref='author', cascade="all, delete-orphan")

    def __init__(self, name, books=None):
        self.name = name
        self.books = books if books is not None else []  # 初始化空列表

    def create(self):
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except Exception as e:
            db.session.rollback()  # 回滚事务
            raise e  # 重新抛出异常
